package com.test.langchain4j.config;

import com.test.langchain4j.service.FunctionAssistant;
import com.test.langchain4j.service.WeatherAssistant;
import com.test.langchain4j.service.WeatherHandler;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolExecutor;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/8/1 18:50
 * @modifiedBy:
 * @version: 1.0
 */
@Configuration
public class LLMConfig {
  @Bean
  public ChatModel chatModel() {
    return OpenAiChatModel.builder()
        .apiKey(System.getenv("qwen-api-key"))
        .modelName("qwen-plus-latest")
        .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
        .build();
  }

  /**
   * Function assistant function assistant.
   * https://docs.langchain4j.dev/tutorials/tools#low-level-tool-api
   *
   * @param chatModel the chat model
   * @return the function assistant @Description: 第一组 Low Level Tool API
   */
  @Bean
  public FunctionAssistant functionAssistant(ChatModel chatModel) {
    // 工具说明 ToolSpecification
    ToolSpecification toolSpecification =
        ToolSpecification.builder()
            .name("开具发票助手")
            .description("根据用户提交的开票信息，开具发票")
            .parameters(
                JsonObjectSchema.builder()
                    .addStringProperty("companyName", "公司名称")
                    .addStringProperty("dutyNumber", "税号序列")
                    .addStringProperty("amount", "开票金额，保留两位有效数字")
                    .build())
            .build();

    // 业务逻辑 ToolExecutor
    ToolExecutor toolExecutor =
        (toolExecutionRequest, memoryId) -> {
          System.out.println(toolExecutionRequest.id());
          System.out.println(toolExecutionRequest.name());
          String arguments1 = toolExecutionRequest.arguments();
          System.out.println("arguments1****》 " + arguments1);
          return "开具成功";
        };

    return AiServices.builder(FunctionAssistant.class)
        .chatModel(chatModel)
        // Tools (Function Calling)
        .tools(Map.of(toolSpecification, toolExecutor))
        .build();
  }

  @Bean
  public WeatherAssistant weatherAssistant(ChatModel chatModel, WeatherHandler weatherHandler) {
    return AiServices.builder(WeatherAssistant.class)
        .chatModel(chatModel)
        // Tools (Function Calling)
        .tools(weatherHandler)
        .build();
  }
}
